package com.bjpowernode.oa.web.action;

import com.bjpowernode.oa.bean.User;
import com.bjpowernode.oa.util.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();
        String username=null;
        String password=null;
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                String name=cookie.getName();
                if("username".equals(name)){
                    username=cookie.getValue();
                }else if("password".equals(name)){
                    password=cookie.getValue();
                }
            }
        }
        if(username!=null&&password!=null){
            //验证用户名和密码是否正确
            //正确成功登录，错误登陆失败
            Connection con=null;
            PreparedStatement pstmt=null;
            ResultSet rs=null;
            int count=0;
            try {
                con= DBUtil.getConnection();
                String sql="select * from t_user where username=? and password=?";
                pstmt=con.prepareStatement(sql);
                pstmt.setString(1,username);
                pstmt.setString(2,password);
                rs=pstmt.executeQuery();
                if(rs.next()){
                    count=1;
                }
            }catch (SQLException e){
                e.printStackTrace();
            }finally{
                DBUtil.close(con,pstmt,rs);
            }
            if(count==1){
                HttpSession session = request.getSession();
                User user=new User(username,password);
                session.setAttribute("user",user);

                //登陆成功
                response.sendRedirect(request.getContextPath()+"/dept/list");
            }else{
                response.sendRedirect(request.getContextPath()+"/index.jsp");
            }
        }else{
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
    }
}
